public class test14 {
    public int[][] generateMatrix(int n) {
        //正方形矩阵
        int[][] res = new int[n][n];
        int tar = n*n;
        int val = 1;
        int l = 0,r = n-1;
        int t = 0,b = n-1;
        while(val<=tar){
            //左-右
            for(int i = l;i<=r;i++){
                res[t][i] = val++;
            }
            t++;
            //上-下
            for(int i = t;i<=b;i++){
                res[i][r] = val++;
            }
            r--;
            //右-左
            for(int i = r;i>=l;i--){
                res[b][i] = val++;
            }
            b--;
            //下-上
            for(int i = b;i>=t;i--){
                res[i][l] = val++;
            }
            l++;
        }
        return res;
    }
}
